<?php

/**
 * Description of UserController
 *
 * @author Poh Nean
 */
class UserController extends PsController
{

	public function accessRules()
	{
		return CMap::mergeArray(array(
					array('allow',
						'users' => array('@'),
						)), parent::accessRules());
	}

	public function filters()
	{
		return CMap::mergeArray(parent::filters(), array(
					'ajaxOnly 
						+ autocomplete'
				));
	}

	public function actionAutocomplete($term, $is = null)
	{
		$validTypes = array('agent');

		if (strlen($term) > 0) {
			$usersArray = array();

			$criteria = new CDbCriteria();
			$criteria->addCondition('(UPPER(username) LIKE :term OR name LIKE :term)');
			$criteria->params[':term'] = "%" . $term . "%";
			$criteria->order = 'name ASC';
			$criteria->limit = 25;

			if (isset($is) && in_array($is, $validTypes)) {
				switch ($is) {
					case 'agent':
						$criteria->addCondition('t.license_no IS NOT NULL');
						break;
				}
			}

			$users = User::model()->ofCurrentAgency()->findAll($criteria);


			if (!empty($users)) {
				foreach ($users as $user) {
					$username = $user->username;
					$name = $user->name;
					$id = $user->id;

					$tmp = array(
						'label' => "[$username] $name",
						'value' => $name,
						'id' => $id,
					);

					$usersArray[] = $tmp;
				}
			}

			print json_encode($usersArray);
		}
	}

}

?>
